﻿using System;
using System.IO;

namespace XTrace
{
	[Obsolete]
	public class TextFileXTraceListener : TextXTraceListener
	{
		string _fileName;
		readonly bool _autoFlush;

		public TextFileXTraceListener(string fileName) : this(fileName, true)
		{
		}

		public TextFileXTraceListener(string fileName, bool autoFlush)
		{
			_fileName = fileName;
			_autoFlush = autoFlush;
			Format = Format.Replace('\t', ',');
			if (!Path.IsPathRooted(fileName))
			{
				throw new Exception("Path is relative. Specify full path.");
			}
		}

		protected override void WriteLine(string line)
		{
			lock (_sync)
			{
				EnsureWriter();
				Writer.WriteLine(line);
				if (_autoFlush)
				{
					Writer.Flush();
				}
			}
		}

		readonly object _sync = new object();

		protected TextWriter Writer;

		private void EnsureWriter()
		{
			if (Writer == null)
			{
				Exception ex_ = null;
				var dir = Path.GetDirectoryName(_fileName);
				var file = Path.GetFileNameWithoutExtension(_fileName);
				var ext = Path.GetExtension(_fileName);

				for (int i = 0; i < 2; i++)
				{
					try
					{
						Writer = new StreamWriter(File.Open(_fileName, FileMode.Append, FileAccess.Write, FileShare.Read));
						ex_ = null;
						break;
					}
					catch(Exception ex)
					{
						file += "_" + Guid.NewGuid().ToString("N");
						_fileName = Path.Combine(dir, file + ext);
						ex_ = ex;
					}
				}

				if (ex_ != null)
				{
					throw ex_;
				}
				WriteColumns();
			}
		}

		protected override void DisposeImpl()
		{
			Writer.Flush();
			base.DisposeImpl();
		}

	}
}